package com.bwie.sms.consumer;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.MessageQueueConstants;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 短信队列消费者。发送短信
 */
@Component
@Log4j2
public class SmsConsumer {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private com.bwie.sms.SendSmsUtils sendSmsUtils;

    @RabbitListener(queuesToDeclare = @Queue(MessageQueueConstants.SEND_SMS))
    public void sendSms(String mobile) {
        log.info("短信消费者接收到消息，消息的内容：{}", mobile);
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        //存储redis
        stringRedisTemplate.opsForValue().set(mobile,code,2, TimeUnit.MINUTES);
        //发送
        sendSmsUtils.sendSms(mobile, JSONObject.toJSONString(new HashMap<String,String>(){{
            put("code", code);
        }}));
        //发送成功之后记录
        stringRedisTemplate.opsForValue().set("SEND_COUNT:"+mobile,"",1,TimeUnit.MINUTES);
        log.info("短信消费者消费信息成功，消息的内容：{}", mobile);
    }

//rabbitTemplate.convertAndSend(MessageQueueConstants.SEND_SMS, mobile);
}
